package com.b2c.repository;

import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.ExpressCompanyEntity;
import com.b2c.entity.OrderCancelEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 描述：
 * 快递公司Repository
 *
 * @author qlp
 * @date 2019-03-08 14:42
 */
@Repository
public class ExpressCompanyRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static Logger log = LoggerFactory.getLogger(ExpressCompanyRepository.class);
    /**
     * 获取快递公司列表
     *
     * @return
     */
    public List<ExpressCompanyEntity> getExpressCompany() {
        String sql = "SELECT * FROM " + Tables.ExpressCompany + " where status=1";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ExpressCompanyEntity.class));
    }

    /**
     * 根据快递公司名查询
     *
     * @param name
     * @return
     */
    public ExpressCompanyEntity getByName(String name) {
        try {
            String sql = "SELECT * FROM " + Tables.ExpressCompany + " WHERE name=? LIMIT 1";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(ExpressCompanyEntity.class), name);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据快递公司编码查询
     *
     * @param code
     * @return
     */
    public ExpressCompanyEntity getByCode(String code) {
        try {
            String sql = "SELECT * FROM " + Tables.ExpressCompany + " WHERE code=? LIMIT 1";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(ExpressCompanyEntity.class), code);
        } catch (Exception e) {
            return null;
        }
    }

    public void update(String code, String name) {

        try{
            String sql = "SELECT * FROM "+ Tables.ExpressCompany + " WHERE code=? or name =? LIMIT 1";
            var model = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(ExpressCompanyEntity.class),code,name);
            jdbcTemplate.update("UPDATE "+ Tables.ExpressCompany +" SET code=?,name=? WHERE id=?",code,name,model.getId());

            log.info("存在，更新"+ JSONObject.toJSONString(model));
        }catch (Exception e){
            String sql = "INSERT INTO "+ Tables.ExpressCompany+" (code,name) VALUE (?,?)";
            jdbcTemplate.update(sql,code,name);
            log.info("不存在，插入{code:"+code+",name:"+name+"}");
        }
    }

}
